package com.wjjm.spoonselling.service.impl;

import com.wjjm.spoonselling.dao.CustomerDao;
import com.wjjm.spoonselling.pojo.Customer;
import com.wjjm.spoonselling.service.CustomerService;
import com.wjjm.spoonselling.util.Code;
import com.wjjm.spoonselling.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Result login(Customer customer) {
        Result result = new Result();
        try{
            Customer c = customerDao.queryMerchantByNameAndPwd(customer);
            if(c == null){
                result.setMsg("用户名或密码错误");
                result.setCode(Code.SELECT_ERR);
            }else {
                result.setMsg("登录成功");
                result.setCode(Code.SELECT_OK);
                customer.setCustomerId(c.getCustomerId());
                result.setData(customer);
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Result register(Customer customer) {
        Result result = new Result();
        try {
            Customer c = customerDao.queryMerchantByName(customer.getName());
            if(c != null){
                //该商家已经存在，不允许注册
                result.setMsg("用户名已存在");
                result.setCode(Code.ADD_ERR);
            }else {
                customerDao.register(customer);
                result.setMsg("注册成功");
                result.setCode(Code.ADD_OK);
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Customer selectByName(String name) {
        Customer customer = customerDao.queryMerchantByName(name);
        return customer;
    }

    @Override
    public boolean update(Customer customer) {
        int i = customerDao.update(customer);
        return i>0;
    }

    @Override
    public boolean updatePassword(Customer customer) {
        String name = customer.getName();
        Customer c = customerDao.queryMerchantByName(name);
        if(c != null){
            int i = customerDao.updatePassword(customer);
            return i>0;
        }else {
            return false;
        }
    }
}
